<template>
  <div>
    <!--在模板里会自动把balabala-->
    <home-header></home-header>
    <!--
      swiperImg是我自己定义的一个变量，这个变量用于被子组件接受
      swiperList是下面data传过来的值
    -->
    <home-swiper :swiperImgList="swiperList"></home-swiper>
    <home-icons :iconsList="iconsList"></home-icons>
    <home-recommend :recommentList="recommentList"></home-recommend>
    <home-weekend :weekendList="weekendList"></home-weekend>
  </div>
</template>

<script>
// eslint-disable-next-line import/no-duplicates
import HomeHeader from './components/Header'
import HomeRecommend from './components/Recommend'
import HomeIcons from './components/Icons'
import HomeSwiper from './components/Swiper'
import HomeWeekend from './components/Weekend'
import axios from 'axios'

import { mapState } from 'vuex'
export default {
  name: 'Home',
  components: {
    // 在es6里面对象的键和值是一样的可以省略
    HomeHeader,
    HomeRecommend,
    HomeIcons,
    HomeSwiper,
    HomeWeekend
  },
  data: function () {
    return {
      lastCity: '',
      swiperList: [],
      iconsList: [],
      recommentList: [],
      weekendList: []
    }
  },
  computed: {
    // 这里顶一个currentCity,这是从vuex里面获取的共享数据
    ...mapState({
      currentCity: 'city'
    })
  },
  methods: {
    getHomeInfo: function () {
      axios.get('/api/index.json?city=' + this.currentCity)
        .then(this.getHomeInfoSuccess)
    },
    getHomeInfoSuccess: function (res) {
      const result = res.data
      if (result.ret && result.data) {
        this.city = result.data.city
        this.swiperList = result.data.swiperList
        this.iconsList = result.data.iconsList
        this.recommentList = result.data.recommentList
        this.weekendList = result.data.weekendList
      }
    }
  },
  // 页面挂在好了之后执行这个函数
  // 每次切换页面重新渲染页面，mounted这个钩子函数都要执行一次
  // 使用keepalive从内存中获取数据，数据不会重新挂在，这个函数不会执行
  mounted: function () {
    this.lastCity = this.currentCity
    this.getHomeInfo()
  },
  // 使用keepalive组件的时候，activated钩子函数被激活,这和钩子函数会被执行
  activated: function () {
    if (this.lastCity !== this.currentCity) {
      // 切换城市的时候改变lastCity
      this.lastCity = this.currentCity
      this.getHomeInfo()
    }
  }
}
</script>
